// pages/index/detail/price/index.js
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
	data: {
    imgurl: app.urlimg,
		title:'',//标题
		head_num: 0,
		comment: [
		],
		// 下拉提示（没有更多）
		without:false,
		//模态框
		isAnimation:false,
		//商品数量
		good_num: 1,
    // 下拉分页
    page:1,
    go_lists:true,
	},

  

//点击排行加载数据

	head_click: function (e) {
		var that = this;
		that.setData({
			head_num: e.currentTarget.dataset.index,
      
		})
   
    var p = e.currentTarget.dataset.index
		console.log(p);

		//数据加载
		wx.request({
      url: app.url + '?controller=api_goods&action=getEkPrice_goods&page=1',
      data: {
        id: that.data.id,
        p: p
      },
			method: 'GET',
			headers: {
				'Content-Type': 'application/json'
			},
			success: function (res) {
        console.log(res.data.result);

        that.setData({
          comment: res.data.result,
          p: p,
          scrollTop:0,
          page: 1,
          //data_Back: json.data.result
        });
			},
			//接口调用失败返回的函数
			fail: function (err) {
				console.log(err)
			}
		})
	},
	//点击进入详情页
	goods_click:function(e){
		var goods_id = e.currentTarget.dataset.goods_id
		console.log(goods_id);
		 wx.navigateTo({ 
       url: '/pages/index/detail/index?id=' + goods_id,
		 })
	},
	//  响应加入购物车
	cart_click:function(e){
		var that=this;
		console.log(e.currentTarget.dataset.goods_id);
		that.setData({
			modal:false,
		})
	},
	//  响应加入购物车
	shopTAP: function (e) {
		this.setData({
			isAnimation2: true,
			actionType: 'cart'
		})

		// 调用动画方法
		moveAnimation(this);
	},
	// 点击加入购物车事件
	xuanfuTAP: function (e) {
		var that = this;
		var isAnimation="";
		console.log(that.data.isAnimation)
		if (that.data.isAnimation){
      isAnimation = false;
      that.setData({
        isAnimation: isAnimation,
      })
		}else{
			isAnimation = true; 
    var goods_id = e.currentTarget.dataset.goods_id
    console.log(goods_id)
    wx.request({
      url: app.url + 'api_goods/goods_detailV1',
      data: {
        id: goods_id,
      },
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
       console.log(res.data.result);

       var spec_array = res.data.result.spec_array;
          var spec_title = ''
          if (!spec_array.length > 0) {
            spec_title = '默认属性'
          } else {
            for (var i = 0; i < spec_array.length; i++) {
              if ((spec_array.length - 1) == i) {
                spec_title += spec_array[i].name
              } else {
                spec_title += spec_array[i].name + '|'
              }
            }
          }

          that.setData({
            data_Back: res.data.result,//获取副本
          data: res.data.result,
          'data.spec_array': spec_array,
          goods_id: res.data.result.id,
          product_id: res.data.result.spec_detail,

          isAnimation: isAnimation,
          goods_thumb: res.data.result.photo[0],
          name: res.data.result.name,
          sell_price: res.data.result.sell_price,
          store_nums: res.data.result.store_nums,
          
        
       })
        console.log(that.data.data.spec_array);
      },
      //接口调用失败返回的函数
      fail: function (err) {
        console.log(err)
      }
    });


    }


	},
  /**
   * 生命周期函数--监听页面加载
   */
	onLoad: function (options) {
    options.id;
    console.log(options);
		var that = this;
		wx.request({
			url: app.url + '?controller=api_goods&action=getEkPrice_goods&page=1',
			data: {
        id: options.id,
        p:2
			},
			header: {
				'content-type': 'application/json',
				'token': wx.getStorageSync('token_key')
			}, 
      
      success: function (json) {
				if (json.data.done == true) {
					//console.log(json.data.result)

          that.setData({
            data_Back: json.data.result,//获取副本
            comment: json.data.result,
            title: json.data.result[0].intro,
            id: options.id,
          });

				} else {
					console.log(555)
					//失败
					// app.apperror(json)
				}

			}, 
		})
	},
	// 响应下一步
	nextStep: function () {
		var that = this
		if (that.data.store_nums == 0) {
			wx.showModal({
				title: '提示',
				content: '商品库存不足！',
			})
			return
		}
		if (this.data.goods_id !== '' && this.data.good_num > 0) {
				//如果是点加入购物的api_order/add_cart?goods_id=384&product_id=5033&number=1 
      var taht = this;
      // console.log(taht.data.goods_id);
      // console.log(taht.data.product_id);
      // console.log(taht.data.good_num);
				wx.request({
					url: app.url + 'api_order/add_cart',
					data: {
						goods_id: taht.data.goods_id,
						product_id: taht.data.product_id,
						number: taht.data.good_num
					},
					header: {
						'content-type': 'application/json',
						'token': wx.getStorageSync('token_key')
					}, success: function (json) {
						if (json.data.done) {
							that.data.data.cart_number = parseInt(that.data.data.cart_number) + parseInt(taht.data.good_num);
							wx.showToast({
								title: '添加购物车成功~',
								icon: 'success',
								duration: 2000
							})
							that.setData({
								isAnimation2: false,
								data: that.data.data
							})
						} else {
							wx.showModal({
								title: '提示',
								content: json.data.message,
							})
						}

					}
				})

		} else {
			wx.showModal({
				title: '提示',
				content: '参数不正常',
			})
		}

	},
	//响应选择按钮
  specTAP: function (e) {
    var that = this

    //获取副本
    var data_Back = that.data.data_Back;
    if (e.currentTarget.dataset.py == "yanse") {
      that.setData({
        data: data_Back,
      })
    }

    console.log(that.data.data.spec_array);
    var py = e.currentTarget.dataset.py;//获取点击的标题
    var spec_array = that.data.data.spec_array;//获取所有样式
    var value = e.currentTarget.dataset.value;//获取选择的颜色
    var spec_detail = that.data.data.spec_detail;//获取所有尺码
    var product_name = [];
    var gobuy = true;
    console.log(spec_array);

    for (var i = 0; i < spec_array.length; i++)//判断选择的样式(颜色或尺码)以及更改显示图片
    {
      if (spec_array[i].py == py) {
        spec_array[i].select = 1;
        that.data.data_Back.spec_array[i].select = 1;
      }
      for (var n = 0; n < spec_array[i].value.length; n++) {
        if (spec_array[i].value[n].value == value) {
          if (typeof (spec_array[i].value[n].img) != 'undefined' && spec_array[i].value[n].img.length > 2) {
            that.setData({ goods_thumb: that.data.imgurl2 + spec_array[i].value[n].img })//更改显示图片


            if (e.currentTarget.dataset.py == "yanse" && spec_array[1] != undefined) {
              var spec_name = [];//获取有存货的商品
              // 点击判断是否有存货
              var size = spec_array[1].value;
              var arr = [];
              //获取用户选择的样式
              for (var g = 0; g < size.length; g++) {
                arr.push("yanse" + value + "chima" + size[g].value)
              }
              // console.log(arr);

              for (var h = 0; h < spec_detail.length; h++) {
                for (var yy = 0; yy < arr.length; yy++) {
                  if (spec_detail[h].spec == arr[yy] && spec_detail[h].store_nums != 0) {
                    product_name.push(spec_detail[h]);
                  }
                }
              }
              // console.log(product_name);

              //获取字符串的函数
              function getStr(string, str) {
                var str_before = string.split(str)[0];
                var str_after = string.split(str)[1];
                return str_after;
              };

              for (var tt = 0; tt < product_name.length; tt++) {
                // var num = product_name[tt].spec.replace(/[^0-9]/ig, "");

                var num = getStr(product_name[tt].spec, 'chima');

                var all = that.data.data_Back.spec_array[1].value;
                var names = '';
                for (var kk = 0; kk < all.length; kk++) {
                  if (all[kk].value == num) {
                    names = all[kk].name;
                  }
                }

                spec_name[tt] = { name: names, img: '', value: num };
              }
              console.log(spec_name);
              that.setData({ 'data.spec_array[1].value': spec_name, })
            }
          }
          spec_array[i].value[n].select = 1;
          that.data.data_Back.spec_array[i].value[n].select = 1;
        } else {
          if (spec_array[i].py == py) {
            spec_array[i].value[n].select = 0;
            that.data.data_Back.spec_array[i].value[n].select = 0;
          }
        }
      }
      spec_array[i].value
    }

    var selectItem = '';//拼接选取的样式
    for (var i = 0; i < spec_array.length; i++) {
      if (!spec_array[i].select) {
        gobuy = false
      } else {
        selectItem += spec_array[i].py
      }
      for (var n = 0; n < spec_array[i].value.length; n++) {
        if (spec_array[i].value[n].select == 1) {
          selectItem += spec_array[i].value[n].value
        }
      }
    }


    if (gobuy) {
      var newdata = that.data.data
      console.log(newdata);
      newdata.store_nums = 0;//初始时，设置产品数量为0
      var product_id = 0//初始时，设置产品编号为0
      for (var i = 0; i < spec_detail.length; i++) {
        if (spec_detail[i].spec == selectItem) {
          if (typeof (newdata.promotion.price) == 'undefined') {
            newdata.sell_price = spec_detail[i].sell_price;
          }
          newdata.store_nums = spec_detail[i].store_nums//产品数量
          product_id = spec_detail[i].product_id//产品编号
        }
      }
      that.setData({
        product_id: product_id,
        data: newdata
      })

    }



    that.data.data.spec_array = spec_array//替换显示
    that.setData({
      data: that.data.data,
    })

  },

	//响应减少按钮
	cutNum: function (e) {
		if (this.data.good_num == 1) {
			return false
		}
		this.setData({ 'good_num': this.data.good_num - 1 })
	},
	//响应添加按钮
	addNum: function (e) {
		this.setData({ 'good_num': this.data.good_num + 1 })
	},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady: function () {

	},

  /**
   * 生命周期函数--监听页面显示
   */
	onShow: function () {

	},

  /**
   * 生命周期函数--监听页面隐藏
   */
	onHide: function () {

	},

  /**
   * 生命周期函数--监听页面卸载
   */
	onUnload: function () {

	},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh: function () {

	},

  /**
   * 页面上拉触底事件的处理函数
   */
	// onReachBottom
  pullUpLoad: function () {
    //提示信息
		var that=this;
    if (that.data.go_lists){
      wx.showToast({
        title: '加载中',
        icon: 'loading',
        duration: 500,
      })
      that.setData({
        go_lists:false,
      });
		console.log("下拉加载更多");
    var page=that.data.page;
    page++;
    console.log(page);
    wx.request({
      url: app.url + '?controller=api_goods&action=getEkPrice_goods&page=' + page,
      data: {
        id: that.data.id,
        p: that.data.p
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      },

      success: function (json) {
        console.log(json);
        if (json.data.result!='') {
          var comment = that.data.comment;
          for (var i = 0; i <json.data.result.length;i++){
            comment.push(json.data.result[i]);
          }
          title: json.data.result.intro
          that.setData({
            comment: comment,
            page: page,
            go_lists:true,
          });

        } else {
          that.setData({
            without: true,
            go_lists: true,
          })
        }

      },
    })
    }

	},

  /**
   * 用户点击右上角分享
   */
	onShareAppMessage: function () {

	}
})
// 动画方法
function moveAnimation(that) {

	var animation = wx.createAnimation({
		duration: 2000,
		timingFunction: 'ease-in-out',
	})

	var h = "auto";
	animation.height(h).translateY(-h).step();
	that.setData({
		animationData: animation.export()
	})
}